package com.kun.kunkunmall.cart.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.kun.common.utils.R;
import com.kun.kunkunmall.cart.feign.ProductFeignService;
import com.kun.kunkunmall.cart.interceptor.CartInterceptor;
import com.kun.kunkunmall.cart.service.CartService;
import com.kun.kunkunmall.cart.vo.Cart;
import com.kun.kunkunmall.cart.vo.CartItem;
import com.kun.kunkunmall.cart.vo.SkuInfoVo;
import com.kun.kunkunmall.cart.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor poolExecutor;

    private final String CART_PREFIX = "kunkunmall:cart:";

    /**
     * 添加商品到购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        // 如果购物车里面有该商品，则无需添加，只需要修改商品数量即可
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();
            // 购物车里面没有该商品
            CompletableFuture<Void> getSkuIfoTask = CompletableFuture.runAsync(() -> {
                // 1.远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = new SkuInfoVo();
                if (r.getCode() == 0) {
                    // 远程调用成功
                    skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    // 2.将商品添加到购物车
                    cartItem.setCheck(true);
                    cartItem.setCount(num);
                    cartItem.setImage(skuInfo.getSkuDefaultImg());
                    cartItem.setTitle(skuInfo.getSkuTitle());
                    cartItem.setSkuId(skuInfo.getSkuId());
                    cartItem.setPrice(skuInfo.getPrice());
                }
            }, poolExecutor);
            // 2.1 远程查询sku的销售属性
            CompletableFuture<Void> getSkuSaleValuesTsk = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, poolExecutor);

            CompletableFuture.allOf(getSkuIfoTask, getSkuSaleValuesTsk).get();
            // 3. 向购物车（redis）保存商品信息
            String cartItemJsonStr = JSONUtil.toJsonStr(cartItem);
            cartOps.put(skuId.toString(), cartItemJsonStr);
            return cartItem;
        } else {
            // 购物车里面有该商品，修改商品数量即可
            CartItem cartItem = JSONUtil.toBean(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            // 重新写到redis当中去
            cartOps.put(skuId.toString(), JSONUtil.toJsonStr(cartItem));
            return cartItem;
        }
    }

    /**
     * 根据skuId获取购物车中的某个购物项
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        return JSONUtil.toBean(o, CartItem.class);
    }

    /**
     * 获取购物车
     *
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 1.判断用户是否登录
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        if (userInfoVo.getUserId() != null) {
            // 用户登录
            String cartKey = CART_PREFIX + userInfoVo.getUserId();
            // 1 获取临时购物车里面购物项
            List<CartItem> cartItemsTemp = getCartItems(CART_PREFIX + userInfoVo.getUserKey());
            if (cartItemsTemp != null && cartItemsTemp.size() > 0) {
                // 1.1 临时购物车有数据，需要合并
                for (CartItem cartItem : cartItemsTemp) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 1.2 合并完成需要清除临时购物车里面的数据
                clearCart(CART_PREFIX + userInfoVo.getUserKey());
            }
            // 2. 获取登录之后的购物车里面的购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        } else {
            // 用户没有登录
            String cartKey = CART_PREFIX + userInfoVo.getUserKey();
            // 获取临时购物车里面的购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;

    }

    /**
     * 获取购物车里面的数据
     *
     * @param cartKey 购物车的键
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map(o -> {
                String str = o.toString();
                return JSONUtil.toBean(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }


    /**
     * 获取用户的购物车redis操作
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoVo.getUserId() != null) {
            // 用户登录了，利用用户的购物车
            cartKey = CART_PREFIX + userInfoVo.getUserId();
        } else {
            // 用户没有登录，利用临时购物车
            cartKey = CART_PREFIX + userInfoVo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 清空购物车
     *
     * @param cartKey 购物车的键
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String jsonStr = JSONUtil.toJsonStr(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonStr);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItem() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        if (userInfoVo != null) {
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoVo.getUserId());
            List<CartItem> itemList = new ArrayList<>();
            if (cartItems != null) {
                // 获取所有被选中的购物车
                itemList = cartItems.stream()
                        .filter(CartItem::getCheck)
                        .peek(cartItem -> {
                            // 获取商品最新的价格，而非是购物车里面的价格
                            BigDecimal price = productFeignService.getPrice(cartItem.getSkuId());
                            cartItem.setPrice(price);
                        })
                        .collect(Collectors.toList());
            }
            return itemList;
        } else {
            return null;
        }
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String jsonStr = JSONUtil.toJsonStr(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonStr);
    }
}
